from flask import g, jsonify, request, url_for, current_app, make_response
from . import api, errors
from .. import db
from ..utils.checkUpload import *
from .lovePost import getVideo
from ..models import *
import traceback


# 测试用
@api.route('/users')
def get_users():
    users = User.query.all()
    return jsonify({'users': [user.to_json() for user in users]})


# √
# 根据user_id获取用户信息
@api.route('/user/<user_id>', methods=['GET'])
def get_user(user_id):
    user = User.query.get_or_404(user_id)

    response = jsonify(user_info=user.to_json())
    response.status_code = 200
    return response

# √
# 更改用户的头像
@api.route('/userAvatar', methods=['POST'])
def edit_user_avatar():
    user = User.query.get(g.current_user.user_id)
    imgUrl, message, status_code = saveImg(request, current_app.config['IMAGES_UPLOAD_FOLDER'])
    if status_code == 200:
        user.avatarUrl = imgUrl
        db.session.commit()

        response = jsonify(message='Upload user: %r avatar successfully!' % user.nickName)
        response.status_code = 200
        return response
    else:
        response = jsonify(error=message)
        response.status_code = status_code
        return response

# √
# 根据user_id获取用户详细信息
@api.route('/userDetail/<user_id>', methods=['GET'])
def get_user_detail(user_id):
    user = User.query.get_or_404(user_id)

    response = jsonify(user_detail=user.to_json_personal_detail())
    response.status_code = 200
    return response

# √
# 修改用户的详细信息
@api.route('/userDetail', methods=['PUT'])
def edit_user_detail():
    user = User.query.get(g.current_user.user_id)
    user.nickName = request.json.get('nickName') if request.json.get('nickName') else user.nickName
    user.gender = request.json.get('gender') if request.json.get('gender') else user.gender
    user.height = request.json.get('height') if request.json.get('height') else user.height
    user.school = request.json.get('school') if request.json.get('school') else user.school
    user.grade = request.json.get('grade') if request.json.get('grade') else user.grade
    user.constellation = request.json.get('constellation') if request.json.get('constellation') else user.constellation
    user.hobby = request.json.get('hobby') if request.json.get('hobby') else user.hobby
    user.personal_sign = request.json.get('personal_sign') if request.json.get('personal_sign') else user.personal_sign
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error=traceback.format_exc())
        response.status_code = 403
        return response
    
    response = jsonify(message='Update user: %r detail information successfully!' % user.nickName)
    response.status_code = 200
    return response

# √
# 关注用户
@api.route('/follows/<int:user_id>', methods=['POST'])
def follow_user(user_id):
    f = follows(user_id=user_id, fans_id=g.current_user.user_id)

    try:
        db.session.add(f)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Follow error!", detail=traceback.format_exc())
        response.status_code = 403
        return response
    print('[+] User: %r follow user: %r' % (g.current_user.user_id, user_id))
    response = jsonify(message="Follow successfully!")
    response.status_code = 200
    return response

# √
# 取消关注
@api.route('/follows/<int:user_id>', methods=['DELETE'])
def unfollow_user(user_id):
    f = follows.query.filter(follows.user_id==user_id, \
                                follows.fans_id==g.current_user.user_id).first_or_404()
    try: 
        db.session.delete(f)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Unfollow error!", detail=traceback.format_exc())
        response.status_code = 403
        return response
    
    print('[-] User: %r unfollow user: %r' % (g.current_user.user_id, user_id))
    response = jsonify(message="Unfollow successfully!")
    response.status_code = 200
    return response

# √
# 查看关注
@api.route('/follows/<int:user_id>', methods=['GET'])
def get_follows(user_id):
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    f = follows.query.filter_by(fans_id=user_id).paginate(int(page), int(pageSize), False).items
    
    if len(f) == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    follow_users = []
    for follow in f:
        follow_user = User.query.get(follow.user_id)
        follow_user_detail = {}
        follow_user_detail['user_id'] = follow_user.user_id
        follow_user_detail['nickName'] = follow_user.nickName
        follow_user_detail['avatarUrl'] = follow_user.avatarUrl
        follow_user_detail['personal_sign'] = follow_user.personal_sign
        follow_users.append(follow_user_detail)

    response = jsonify(message='Get follows data successfully!', follows=follow_users)
    response.status_code = 200
    return response

# √
# 查看粉丝
@api.route('/fans/<int:user_id>', methods=['GET'])
def get_fans(user_id):
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    f = follows.query.filter_by(user_id=user_id).paginate(int(page), int(pageSize), False).items

    if len(f) == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    fans = []
    for follow in f:
        fans_user = User.query.get(follow.fans_id)
        fans_user_detail = {}
        fans_user_detail['user_id'] = fans_user.user_id
        fans_user_detail['nickName'] = fans_user.nickName
        fans_user_detail['avatarUrl'] = fans_user.avatarUrl
        fans_user_detail['personal_sign'] = fans_user.personal_sign
        fans.append(fans_user_detail)

    response = jsonify(message='Get fans data successfully!', fans=fans)
    response.status_code = 200
    return response

# √
# 添加收藏
@api.route('/collections/<int:lovePostId>', methods=['POST'])
def add_collection(lovePostId):   
    try:
        c = userCollection(user_id=g.current_user.user_id, love_post_id=lovePostId)
        db.session.add(c)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Collected error!", detail=traceback.format_exc())
        response.status_code = 403
        return response

    response = jsonify(message="Collected successfully!")
    response.status_code = 200
    return response

# √
# 取消收藏
@api.route('/collections/<lovePostId>', methods=['DELETE'])
def del_collection(lovePostId):
    c = userCollection.query.filter(userCollection.love_post_id==lovePostId, \
                                    userCollection.user_id==g.current_user.user_id).first_or_404()
    try:
        db.session.delete(c)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="UnCollected error!", detail=traceback.format_exc())
        response.status_code = 403
        return response

    response = jsonify(message="UnCollected successfully!")
    response.status_code = 200
    return response

# √
# 查看个人收藏
@api.route('/collections', methods=['GET'])
def get_collections():
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 50
    u_collections = userCollection.query.filter_by(user_id=g.current_user.user_id).paginate(int(page), int(pageSize), False).items

    if len(u_collections) == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    love_posts = [u_collection.lovepost for u_collection in u_collections]
    u_collections = [l.to_json() for l in u_collections]

    for u_collection, love_post in zip(u_collections, love_posts):
        u_collection['media_type'] = love_post.media_type
        u_collection['describe'] = love_post.describe

        if u_collection['media_type'] == 'img':
            img = image.query.filter(image.love_post_id==u_collection['love_post_id'], \
                                        image.sequence_num==0).first()
            u_collection['imgUrl'] = img.img_url

        if u_collection['media_type'] == 'video':
            v = video.query.filter_by(love_post_id=u_collection['love_post_id']).first()
            u_collection['videoUrl'] = getVideo(v.aliyun_video_id)
    
    u_collections.reverse()
    response = jsonify(message='Get user collections data successfully!', collections=u_collections)
    response.status_code = 200
    return response

# √
# 查看个人动态
@api.route('/userTrends/<int:user_id>', methods=['GET'])
def get_user_trends(user_id):
    user = User.query.get_or_404(user_id)
    visit_user_fans = follows.query.filter_by(user_id=user_id).all()
    visit_user_fans = [f.fans_id  for f in visit_user_fans]

    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    u_trends = userTrends.query.filter_by(user_id=user_id).order_by(userTrends.trends_id.desc()).paginate(int(page), int(pageSize), False).items

    is_fans = True if g.current_user.user_id in visit_user_fans else False

    if len(u_trends) == 0:
        response= jsonify(
            message='No publish love_post!', 
            user_detail=user.to_json_personal_detail(), 
            is_fans=is_fans,
            trends_count=0
    )
        response.status_code = 200
        return response

    if len(u_trends) == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    # countOfAlbum = 0
    # countOfText = 0
    love_posts = [u_trend.lovepost for u_trend in u_trends]
    u_trends = [l.to_json() for l in u_trends]

    for u_trend, love_post in zip(u_trends, love_posts):   
        u_trend['media_type'] = love_post.media_type
        u_trend['describe'] = love_post.describe
        u_trend['publish_time'] = str(love_post.publish_time).split('.')[0]

        # if u_trend['media_type'] == 'text':
        #     countOfText += 1
        
        if u_trend['media_type'] == 'img':
            # countOfAlbum += 1
            img = image.query.filter(image.love_post_id==u_trend['love_post_id'], image.sequence_num==0).first()
            u_trend['imgUrl'] = img.img_url

        if u_trend['media_type'] == 'video':
            v = video.query.filter_by(love_post_id=u_trend['love_post_id']).first()
            u_trend['videoUrl'] = getVideo(v.aliyun_video_id)


    response = jsonify(
        message='Get user trends data successfully!', 
        userTrends=u_trends, 
        user_detail=user.to_json_personal_detail(), 
        is_fans=is_fans, 
        # countOfAlbum=countOfAlbum, 
        # countOfText=countOfText,
        trends_count=user.trends_count
    )
    response.status_code = 200
    return response

# √
# 查看消息列表
@api.route('/messageList', methods=['GET'])
def get_message_list():
    # 返回的每一条数据包括：
    # [动作产生者的头像] xxx 评论/赞/关注/回复 了你的 动态/评论 [动态图片(没图的文字)]
    # 获取当前用户的消息列表
    message_list = messageList.query.filter_by(user_id=g.current_user.user_id).order_by(messageList.message_id.desc())
    message_list = [m.to_json() for m in message_list]

    if len(message_list) == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    messageBox = []

    for message in message_list:
        mb = {}
        # 获取动作产生者
        messageCreator = User.query.get_or_404(message['message_creator'])
        # 获取动作产生者的头像
        mb['messageCreatorAvatarUrl'] = messageCreator.avatarUrl
        mb['messageCreatorNickName'] = messageCreator.nickName
        mb['refer_id'] = message['refer_id']
        mb['create_time'] = message['create_time']
        # 消息类型：新增粉丝addFans/被回复reviewed(表白墙或评论)/评论被点赞commentLiked/表白墙被喜欢lovePostLiked
        if message['message_type'] == 'addFans':
            mb['message'] = '关注了你'
        elif message['message_type'] == 'reviewed':
            mb['message'] = '回复了你'
        elif message['message_type'] == 'commentLiked':
            mb['message'] = '赞了你的评论'
        elif message['message_type'] == 'lovePostLiked':
            mb['message'] = '赞了你的动态'

        if message['message_type'] in ['reviewed', 'commentLiked', 'lovePostLiked']:
            love_post = lovePost.query.get(message['refer_id'])
            mb['meida_type'] = love_post.media_type

            if mb['meida_type'] == 'img':
                img = image.query.filter(image.love_post_id==love_post.love_post_id, \
                                        image.sequence_num==0).first()
                mb['imgUrl'] = img.img_url
            elif mb['meida_type'] == 'video':
                v = video.query.filter_by(love_post_id=love_post.love_post_id).first()
                mb['videoUrl'] = getVideo(v.aliyun_video_id)
            else:
                mb['describe'] = love_post.describe[:20]
        
        messageBox.append(mb)

    response = jsonify(message='Get message list successfully!', messageList=messageBox)
    response.status_code = 200
    return response


# √
# 清空消息列表
@api.route('/messageList', methods=['DELETE'])
def drop_message_list():
    message_list = messageList.query.filter_by(user_id=g.current_user.user_id).all()
    for m in message_list:
        try:
            db.session.delete(m)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            response = jsonify(error="Drop message list error!", detail=traceback.format_exc())
            response.status_code = 403
            return response

    response = jsonify(message="Drop message list successfully!")
    response.status_code = 200
    return response


